<?php

class LoginActions extends sfActions {

    public function executeLogin(sfWebRequest $request) {
        if ($this->getUser()->isAuthenticated() ) {
            $this->redirect("default/index");
        } else {
            $this->form = new loginForm();
            $this->error = '';
            
            if ($request->isMethod(sfRequest::POST)) {
                $this->processLoginForm($request, $this->form);
            }
        }
    }

    protected function processLoginform(sfWebRequest $request, sfForm $form) {

        $ValuesArray = $request->getParameter($form->getName());
        $form->bind($ValuesArray, $request->getFiles($form->getName()));

        if ($form->isValid()) {
            $user = User::getValidUser($form['username']->getValue(), $form['password']->getValue());
            if ($user){
            $user = User::getUserByUserNames($form['username']->getValue());
            $this->getUser()->setAttribute('User', $user);
            $this->getUser()->setAttribute('Username', $user->getFirstName()." ".$user->getLastName());
            $this->getUser()->setAuthenticated(true);
            $this->redirect("default/index");
            }else {
                $this->error = "Username and Password is incorrect";
            }
        }
    }

    public function executeLogout(sfWebRequest $request) {
        if ($this->getUser()->hasAttribute('User')) {
            $this->getUser()->getAttributeHolder()->clear();
            $this->getUser()->setAuthenticated(false);
        }
          $this->redirect('login/login');   
    }

}